const db = wx.cloud.database()
const userInfo = db.collection('userInfo')
const userCollection = db.collection('user')
//获取应用实例
const app = getApp()

Page({
  data: {
    username: '',
    num: '',
    sex: '',
    grade: '',
    class: '',
    qq: '',
    user: [],
    userList: [],
  },
  bindNameInput(e) {
    this.setData({
      username: e.detail.value
    })
  },
  bindSexInput(e) {
    this.setData({
      sex: e.detail.value
    })
  },
  bindNumInput(e) {
    this.setData({
      num: e.detail.value
    })
  },
  bindGradeInput(e) {
    this.setData({
      grade: e.detail.value
    })
  },
  bindClassInput(e) {
    this.setData({
      class: e.detail.value
    })
  },
  bindQQInput(e) {
    this.setData({
      qq: e.detail.value
    })
  },


  onLoad: function (options) {
    console.log(options)
    userInfo.get().then(res => {
      console.log(res.data)
      if (res.data != null) {
        this.setData({
          userList: res.data,
          isDisplay: false
        })
      }
    })

    userCollection.where({
      _openid: options.openid
    }).get().then(res => {
      console.log(res.data)
      this.setData({
        user: res.data,
      })
    })

    wx.setNavigationBarTitle({
      title: '编辑资料'
    })
  },

  bindSaveTap() {
    console.log(this.data.userList[0].avatarUrl)
    wx.cloud.callFunction({
      name: 'updateUser',
      data: {
        id: this.data.user[0]._id,
        username: this.data.username,
        avatar: this.data.userList[0].avatarUrl,
        sex: this.data.sex,
        num: this.data.num,
        grade: this.data.grade,
        class: this.data.class,
        qq: this.data.qq,
      },
      success: res => {
        console.log(res)
        wx.showToast({
          title: '修改成功',
        })
        wx.navigateBack({
          delta: 1
        })
      },
      fail: function () {
        wx.showToast({
          title: '修改失败',
        })
      }
    })
  },
})